package cn.itcast.service.impl;

import cn.itcast.entity.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.mapper.MemberMapper;
import cn.itcast.mapper.OrderMapper;
import cn.itcast.mapper.OrderSettingMapper;
import cn.itcast.pojo.Member;
import cn.itcast.pojo.Order;
import cn.itcast.pojo.OrderSetting;
import cn.itcast.pojo.vo.OrderVO;
import cn.itcast.service.OrderService;
import cn.itcast.utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderSettingMapper orderSettingMapper;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    OrderMapper orderMapper;

    @Transactional
    public Result order(Map map) throws Exception {
        //条件1：检查该日期是否可以进行预约
        String orderDate = map.get("orderDate").toString();
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting os = orderSettingMapper.findByOrderDate(date);
        if(os==null){
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }


        //条件2：该日期预约人数是否已满
        int reservations = os.getReservations();
        if(reservations>=os.getNumber()){
            return new Result(false, MessageConstant.ORDER_FULL);
        }


        //条件3：不可以重复预约
        String telephone = map.get("telephone").toString();
        Member member = memberMapper.findByTelephone(telephone);
        if(member!=null){
            //根据客户id、套餐id、日期查寻，检查数据库中是否有重复的记录
            Integer id = member.getId();
            String setmealId = map.get("setmealId").toString();
            Order order = new Order(id, date, Integer.valueOf(setmealId));

            //如果list!=null代表有重复记录，则返回错误提示信息
            List<Order> list = orderMapper.findByCondition(order);
            if(list!=null && list.size()>0){
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else{
            //自动注册会员
            memberMapper.add(map);
        }



        Order order = new Order();
        order.setMemberId(Integer.valueOf(map.get("id").toString()));
        order.setOrderDate(date);
        order.setOrderType(map.get("orderType").toString());
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.valueOf(map.get("setmealId").toString()));



        orderMapper.add(order);

        os.setReservations(reservations+1);
        orderSettingMapper.editNumberByOrderDate(os);


        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS,order.getId());
    }



    public OrderVO findById(int id) {

        return orderMapper.findById4Detail(id);
    }
}
